package com.example.dict.ativities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.example.dict.R;
import com.example.dict.bean.TuwenBean;
import com.example.dict.utils.FileUtil;
import com.example.dict.utils.PatternUtils;
import com.example.dict.utils.RecognizeService;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {


    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    Toolbar mToolbar;
    TextView mPytext,mBuShtext,mChyutext,mTuwentext,mContent,mSource;
    EditText mZiet;
    private long firstTime = 0;

    private boolean hasGotToken = false;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106; //请求码
    private AlertDialog.Builder alertDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        initView();
        alertDialog = new AlertDialog.Builder(this);
        initAccessTokenWithAkSk();
    }

    /*把menu.xml文件装载到APP中*/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    /**
     * toolbar 的监听事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }
    /**
     * 图文识别部分
     */
    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }
            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "2suF59R8detTycwDiaffHHoT", "kjTNOz1i2rO17VKlfOoBnaPwnyoPYTxG");
    }
    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recGeneralBasic(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
//                            Log.i("animee","onResult:result="+result);
                            //result是识别出的字符串，可以将字符串传递给下一个界面
                            TuwenBean wenBean = new Gson().fromJson(result, TuwenBean.class);
                            List<TuwenBean.WordsResultBean> wordsList = wenBean.getWords_result();
                            //将提取到的有用的汉字存放到集合当中，传递到下一个界面
                            ArrayList<String> list = new ArrayList<>();
                            if (wordsList!=null&&wordsList.size()!=0) {
                                for (int i = 0; i < wordsList.size(); i++) {
                                    TuwenBean.WordsResultBean bean = wordsList.get(i);
                                    String words = bean.getWords();
                                    String res = PatternUtils.removeAll(words);//剔除所有的数字、字母，标点符号，拿到纯汉字
                                   //将字符串当中每一个字符串都添加到集合当中
                                    for (int j = 0; j < res.length(); j++) {
                                        String s = String.valueOf(res.charAt(j));// 将字符转换成字符串
                                      // 添加集合之前，先判断一下，集合是否包括这个汉字
                                        if (!list.contains(s)) {
                                            list.add(s);
                                        }
                                    }
                                }
//                                判断是否有可识别的文字
                                if (list.size()==0) {
                                    Toast.makeText(MainActivity.this,"无法识别图片中的文字！",Toast.LENGTH_SHORT).show();
                                }else{
                                    Intent it = new Intent(MainActivity.this, IdentifyImgActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putStringArrayList("wordlist",list);
                                    it.putExtras(bundle);
                                    startActivity(it);
                                }
                            }
                        }
                    });
        }
    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        // 释放内存资源
//        OCR.getInstance(this).release();
//    }



    /**
     * 初始化数据
     */
    private void initView() {
        mPytext = findViewById(R.id.main_pinyin);
        mBuShtext = findViewById(R.id.mmain_bushou);
        mChyutext = findViewById(R.id.main_chengyu);
        mTuwentext = findViewById(R.id.main_tuwen);
        mContent = findViewById(R.id.m_content);
        mSource = findViewById(R.id.m_source);
        mZiet = findViewById(R.id.main_et);
        mDrawerLayout = findViewById(R.id.drawer_view);
        mNavigationView = findViewById(R.id.nav_view);

        //toolbar
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_menu);
        }
        mNavigationView.setItemIconTintList(null);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.collection:
                        Intent intent = new Intent();
                        intent.setClass(getBaseContext(),CollectionActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.feedback:

                        break;
                    case R.id.good:

                        break;
                    case  R.id.share:
                       shareSoftware();
                        break;
                    case R.id.aboutus:

                        break;
                }
                return false;
            }

            private void shareSoftware() {
                //分享这个软件到其他用户
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                String msg = "遇到不熟悉的汉字和成语？下载中华字典就可以查看啦~";
                intent.putExtra(Intent.EXTRA_TEXT,msg);
                startActivity(Intent.createChooser(intent,"分享到......"));
            }
        });
    }

    /**
     * 点击返回键调用的方法
     */
    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }else {
            if (System.currentTimeMillis()-firstTime >2000) {
                Toast.makeText(MainActivity.this,"再次点击退出程序",Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }else {
                super.onBackPressed();
            }

        }
    }

    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()){
            case R.id.ic_search:
               //拿到搜索框中写入的字
                String text = mZiet.getText().toString();
                    if (!TextUtils.isEmpty(text)) {
                        intent = intent.setClass(this, WordInfoActivity.class);
                        intent.putExtra("zi",text);
                        startActivity(intent);
                    }
                break;
            case R.id.main_pinyin:
                intent.setClass(this,QueryPinyinActivity.class);
                startActivity(intent);
                break;
            case R.id.mmain_bushou:
                intent.setClass(this,QueryBushouActivity.class);
                startActivity(intent);
                break;

            case R.id.main_chengyu:
                 intent.setClass(this,QueryChengYuActivity.class);
                 startActivity(intent);
                break;
            case R.id.main_tuwen:
                if (!checkTokenStatus()) {
                    return;
                }
                intent.setClass(MainActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);
                break;

        }
    }

}
